/**
 * 
 */
package org.nahtanoj.contacts;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;

import org.nahtanoj.contacts.sheet.Sheet;

import com.google.gdata.util.AuthenticationException;
/**
 * @author jm
 *
 */
public class ContactStoreDocs implements ContactStore {
	private static final Logger log = Logger.getLogger(ContactStoreDocs.class.getName());
	private final HashMap<String, Contact> contacts = new HashMap<String, Contact>();
	private int lastUsedRow = 0;
	private Sheet s;
	private HashMap<String, Contact> matched;
	private HashMap<String, Contact> newDocs;
	private HashMap<String, Contact> newMail;

	/**
	 * @throws AuthenticationException
	 * 
	 */
	public ContactStoreDocs() throws AuthenticationException {
		if (this.s == null) {
			//TODO is this always j - might as well be
			this.s = new Sheet("j", "Contacts", "Contacts", 1);
		}
		log.info("" + this.s.getRowCount());
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#addContact(org.nahtanoj.contacts.Contact)
	 */
	@Override
	public void add(Contact c) {
		// Zero means add to the end
		if (c.getRow() == 0) {
			this.lastUsedRow = this.lastUsedRow + 1;
		}
		if (c.getHash() == null) {
			c.setHash("a");
		}
		while (contacts.get(c.getHash()) != null) {
			c.setHash(c.getHash() + "a");
		}
		//		if (contacts.get(c.getHash()) != null) {
		//			if (c.getHash() == null) {
		//				c.hashUpdate();
		//			} else {
		//				log.warning("Duplicate mail hash:" + c.getHash() + " " + c.getLastName() + " " + c.getFirstName());
		//			}
		//		}
		contacts.put(c.getHash(), c);
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#drop(org.nahtanoj.contacts.Contact)
	 */
	@Override
	public void drop(Contact c) {
		// TODO should we ever drop here?
		log.warning("Dropping from docs:" + c);
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#getContacts()
	 */
	@Override
	public HashMap<String, Contact> getContacts() {
		return this.contacts;
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#getMatched()
	 */
	@Override
	public HashMap<String, Contact> getMatched() {
		return this.matched;
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#getNewDocs()
	 */
	@Override
	public HashMap<String, Contact> getNewDocs() {
		return this.newDocs;
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#getNewMail()
	 */
	@Override
	public HashMap<String, Contact> getNewMail() {
		return this.newMail;
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#loadContacts()
	 */
	@Override
	public void load() {
		String colContacts[][] = s.getValues("Last Name", 2, "Validation", s.getRowCount());
		String rowContacts[][] = new String[colContacts[0].length][colContacts.length];

		for (int c = 0; c < colContacts.length; c++) {
			for (int r = 0; r < colContacts[c].length; r++) {
				rowContacts[r][c] = colContacts[c][r];
			}
		}
		for (int i = 0; i < rowContacts.length; i++) {
			String[] contact = rowContacts[i];
			boolean isNull = true;
			for (String f : contact) {
				if (f != null) {
					isNull = false;
				}
			}
			if (isNull == false) {
				this.lastUsedRow = i;
				Contact c = new Contact(contact, i + 2);
				add(c);
			}
		}
		this.lastUsedRow = this.lastUsedRow + 2; // Header and because count starts at zero
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#saveContacts()
	 */
	@Override
	public void save() {
		try {
			FileWriter fw = new FileWriter("CSD.csv");
			fw.write("\"Last Name\",\"First Name\",\"Business\",\"Home\",\"Mobile\",\"Mobile 2\",\"E-mail Address\",\"E-mail 2 Address\",\"Home Street\",\"Home Street 2\",\"Home City\",\"Home State\",\"Home Postal Code\",\"Home Country\",\"Birthday\",\"Anniversary\",\"Category\",\"Children\",\"Notes\",\"ContactSync\",\"Hash\",\"Validation\"\n");
			for (Contact c : this.contacts.values()) {
				c.hashUpdate();
				fw.write("\"");
				if (c.getLastName() != null) {		fw.write(c.getLastName()); }		fw.write("\",\"");
				if (c.getFirstName() != null) {		fw.write(c.getFirstName()); }		fw.write("\",\"");
				if (c.getBusiness() != null) {		fw.write(c.getBusiness()); }		fw.write("\",\"");
				if (c.getHome() != null) {			fw.write(c.getHome()); }			fw.write("\",\"");
				if (c.getMobile() != null) {		fw.write(c.getMobile()); }			fw.write("\",\"");
				if (c.getMobile2() != null) {		fw.write(c.getMobile2()); }			fw.write("\",\"");
				if (c.getEmailAddress() != null) {	fw.write(c.getEmailAddress()); }	fw.write("\",\"");
				if (c.getEmail2Address() != null) {	fw.write(c.getEmail2Address()); }	fw.write("\",\"");
				if (c.getHomeStreet() != null) {	fw.write(c.getHomeStreet()); }		fw.write("\",\"");
				if (c.getHomeStreet2() != null) {	fw.write(c.getHomeStreet2()); }		fw.write("\",\"");
				if (c.getHomeCity() != null) {		fw.write(c.getHomeCity()); }		fw.write("\",\"");
				if (c.getHomeState() != null) {		fw.write(c.getHomeState()); }		fw.write("\",\"");
				if (c.getHomePostalCode() != null) {fw.write(c.getHomePostalCode()); }	fw.write("\",\"");
				if (c.getHomeCountry() != null) {	fw.write(c.getHomeCountry()); }		fw.write("\",\"");
				if (c.getBirthday() != null) {		fw.write(c.getBirthday()); }		fw.write("\",\"");
				if (c.getAnniversary() != null) {	fw.write(c.getAnniversary()); }		fw.write("\",\"");
				if (c.getCategory() != null) {		fw.write(c.getCategory()); }		fw.write("\",\"");
				if (c.getChildren() != null) {		fw.write(c.getChildren()); }		fw.write("\",\"");
				if (c.getNotes() != null) {			fw.write(c.getNotes()); }			fw.write("\",\"");
				if (c.getContactSync() != null) {	fw.write(c.getContactSync()); }		fw.write("\",\"");
				if (c.getHash() != null) {			fw.write(c.getHash()); }			fw.write("\",\"");
				if (c.getValidation() != null) {	fw.write(c.getValidation()); }		fw.write("\"\n");
			}
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		for (String h : this.getContacts().keySet()) {
			Contact c = this.getContacts().get(h);
			if (c.hashCheck() == false) {
				//TODO				saveContact(c);
				System.out.println("Saving:" + c);
			}
		}
	}

	//TODO update the hash
	//TODO commit the changes- I think that is all that needs changing
	private void saveContact(Contact c) {
		int r = c.getRow();
		if (c.getLastName() != null) {
			this.s.setValue("Last Name", r, c.getLastName());
		}
		if (c.getFirstName() != null) {
			this.s.setValue("First Name", r, c.getFirstName());
		}
		if (c.getBusiness() != null) {
			this.s.setValue("Business", r, c.getBusiness());
		}
		if (c.getHome() != null) {
			this.s.setValue("Home", r, c.getHome());
		}
		if (c.getMobile() != null) {
			this.s.setValue("Mobile", r, c.getMobile());
		}
		if (c.getMobile2() != null) {
			this.s.setValue("Mobile 2", r, c.getMobile2());
		}
		if (c.getEmailAddress() != null) {
			this.s.setValue("E-mail Address", r, c.getEmailAddress());
		}
		if (c.getEmail2Address() != null) {
			this.s.setValue("E-mail 2 Address", r, c.getEmail2Address());
		}
		if (c.getHomeStreet() != null) {
			this.s.setValue("Home Street", r, c.getHomeStreet());
		}
		if (c.getHomeStreet2() != null) {
			this.s.setValue("Home Street 2", r, c.getHomeStreet2());
		}
		if (c.getHomeCity() != null) {
			this.s.setValue("Home City", r, c.getHomeCity());
		}
		if (c.getHomeState() != null) {
			this.s.setValue("Home State", r, c.getHomeState());
		}
		if (c.getHomePostalCode() != null) {
			this.s.setValue("Home Postal Code", r, c.getHomePostalCode());
		}
		if (c.getHomeCountry() != null) {
			this.s.setValue("Home Country", r, c.getHomeCountry());
		}
		if (c.getBirthday() != null) {
			this.s.setValue("Birthday", r, c.getBirthday());
		}
		if (c.getAnniversary() != null) {
			this.s.setValue("Anniversary", r, c.getAnniversary());
		}
		if (c.getCategory() != null) {
			this.s.setValue("Category", r, c.getCategory());
		}
		if (c.getNotes() != null) {
			this.s.setValue("Notes", r, c.getNotes());
		}
		if (c.getContactSync() != null) {
			this.s.setValue("ContactSync", r, c.getContactSync()); // Blank so it doesn't get repeated
		}
		if (c.getChildren() != null) {
			this.s.setValue("Children", r, c.getChildren());
		}
		//		this.s.setValue("Validation", r, "New contact from gmail\n" + c.isValid());
		c.setRow(r);
		c.hashUpdate();
		this.s.setValue("Hash",  r,  c.getHash());
		s.submit();
	}

	/* (non-Javadoc)
	 * @see org.nahtanoj.contacts.ContactStore#setMatches(java.util.HashMap, java.util.HashMap, java.util.HashMap)
	 */
	@Override
	public void setMatches(HashMap<String, Contact> ms,
			HashMap<String, Contact> ud, HashMap<String, Contact> us) {
		this.matched = ms;
		this.newDocs = ud;
		this.newMail = us;
	}

}
